package logic

import (
	"context"
	"errors"
	"furni-set/models/mysql"

	"furni-set/setrpc/internal/svc"
	"furni-set/setrpc/setrpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *setrpc.GoodsAddRequest) (*setrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	//防止重复商品同名，
	var good mysql.Goods
	err := good.FindGoods(mysql.DB, in.Name)
	if err == nil {
		return nil, errors.New("商品已存在")
	}

	class := &mysql.Class{
		Model: gorm.Model{},
		Name:  in.ClassName,
	}
	if err = class.FindClass(mysql.DB, in.ClassName); err != nil {
		return nil, err
	}
	goods := &mysql.Goods{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		ClassId: int64(class.ID),
	}
	if err = goods.GoodsAdd(mysql.DB); err != nil {
		return nil, err
	}
	return &setrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
